// System predefined templates
const SYSTEM_TEMPLATES = {
    'sys_bank_default': {
        id: 'sys_bank_default',
        name: '银行流水通用模板',
        dataType: 'bank',
        isSystem: true,
        mappings: {
            '交易时间': 'transaction_time',
            '交易日期': 'transaction_time',
            '发生时间': 'transaction_time',
            '本方账号': 'account_number',
            '账号': 'account_number',
            '卡号': 'account_number',
            '交易金额': 'transaction_amount',
            '发生额': 'transaction_amount',
            '金额': 'transaction_amount',
            '借贷标志': 'debit_credit_flag',
            '对方户名': 'counterparty_name',
            '对方姓名': 'counterparty_name',
            '对方账号': 'counterparty_account',
            '对方卡号': 'counterparty_account',
            '摘要': 'remarks',
            '备注': 'remarks',
            '余额': 'balance_after'
        }
    },
    'sys_call_default': {
        id: 'sys_call_default',
        name: '话单通用模板',
        dataType: 'call',
        isSystem: true,
        mappings: {
            '机主姓名': 'user_name',
            '本机号码': 'user_number',
            '主叫号码': 'user_number',
            '对方号码': 'opp_user_number',
            '被叫号码': 'opp_user_number',
            '通话时间': 'start_time',
            '起始时间': 'start_time',
            '通话时长': 'duration',
            '时长': 'duration',
            '呼叫类型': 'call_type',
            '主被叫': 'call_type',
            '通话地点': 'location'
        }
    }
}

export class TemplateManager {
    static getAllTemplates() {
        let userTemplates = {}
        try {
            const stored = localStorage.getItem('fieldTemplates')
            if (stored) {
                userTemplates = JSON.parse(stored)
            }
        } catch (e) {
            console.error('读取本地模板失败', e)
        }
        return { ...SYSTEM_TEMPLATES, ...userTemplates }
    }

    static saveUserTemplate(name, dataType, mappings) {
        try {
            const templates = JSON.parse(localStorage.getItem('fieldTemplates') || '{}')
            const id = `user_tpl_${Date.now()}`

            templates[id] = {
                id,
                name,
                dataType,
                mappings,
                isSystem: false,
                createTime: new Date().toISOString()
            }

            localStorage.setItem('fieldTemplates', JSON.stringify(templates))
            return { success: true, id }
        } catch (e) {
            console.error('保存模板失败', e)
            return { success: false, message: e.message }
        }
    }

    static deleteUserTemplate(id) {
        try {
            if (SYSTEM_TEMPLATES[id]) {
                return { success: false, message: '系统内置模板无法删除' }
            }
            const templates = JSON.parse(localStorage.getItem('fieldTemplates') || '{}')
            if (templates[id]) {
                delete templates[id]
                localStorage.setItem('fieldTemplates', JSON.stringify(templates))
                return { success: true }
            }
            return { success: false, message: '模板不存在' }
        } catch (e) {
            console.error('删除模板失败', e)
            return { success: false, message: e.message }
        }
    }

    static tryAutoMapFromTemplate(dataType, headers) {
        const allTemplates = Object.values(this.getAllTemplates())
        const candidates = allTemplates.filter(t => t.dataType === dataType)

        if (candidates.length === 0) return null

        let bestTemplate = null
        let maxMatchCount = 0
        const normalizedHeaders = headers.map(h => String(h).trim().toLowerCase())

        for (const tpl of candidates) {
            let matchCount = 0
            const mappings = tpl.mappings || {}

            for (const sourceField of Object.keys(mappings)) {
                const normSource = sourceField.trim().toLowerCase()
                // Check for exact match or substring match
                if (normalizedHeaders.includes(normSource) || normalizedHeaders.some(h => h.includes(normSource))) {
                    matchCount++
                }
            }

            if (matchCount > maxMatchCount) {
                maxMatchCount = matchCount
                bestTemplate = tpl
            }
        }

        // Require at least 2 matches to consider it a valid template match
        if (bestTemplate && maxMatchCount >= 2) {
            return bestTemplate
        }

        return null
    }
}
